import 'package:flutter/cupertino.dart';
import 'package:flutter_project/common/utils/screen_size_utils.dart';
import 'package:flutter_project/config/app_bar_view.dart';
import 'package:flutter_project/config/loading_toast.dart';
import 'package:get/get.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import '../../config/theme_color.dart';

class ScanMainPage extends StatefulWidget {
  const ScanMainPage({super.key});

  @override
  State<ScanMainPage> createState() => _ScanMainPageState();
}

class _ScanMainPageState extends State<ScanMainPage>
    with SingleTickerProviderStateMixin {
  late AnimationController animationController;
  late Animation _animation;
  final MobileScannerController mobileScannerController =
      MobileScannerController();

  @override
  Widget build(BuildContext context) {
    return CommonAppWidget.navAppBar(
      title: '扫一扫',
      childWidget: Stack(
        children: [
          MobileScanner(
            // fit: BoxFit.contain,
            controller: mobileScannerController,
            onDetect: (capture) {
              final List<Barcode> barcodes = capture.barcodes;
              String? codeString;
              for (final barcode in barcodes) {
                if (barcode.rawValue!.isNotEmpty) {
                  debugPrint('Barcode found! ${barcode.rawValue}');
                  codeString = barcode.rawValue!;
                  break;
                }
              }
              getCodeFormPic(codeString ?? '');
            },
          ),
          AnimatedBuilder(
            builder: (cxt, child) {
              return Container(
                // width: 5, 设了宽度之后，动画没了，不知道为啥
                margin: EdgeInsets.fromLTRB(
                    37.5, 50.0 + _animation.value, 37.5, 133),
                child: child,
              );
            },
            animation: animationController,
            child: Image.asset("assets/images/scan/scanning_line.png",
                color: ThemeColor.mainColor,
                fit: BoxFit.fill,
                width: double.infinity),
          ),
          getTorchLightView(),
        ],
      ),
    );
  }

  //手电筒和文字布局
  Widget getTorchLightView() {
    return GestureDetector(
      onTap: () {
        mobileScannerController.toggleTorch();
      },
      child: Center(
        child: Container(
          width: 70,
          height: 54,
          margin: EdgeInsets.only(
              top: ScreenSizeUtils.deviceScreenHeight(Get.context!) -
                  ScreenSizeUtils.safeStatusScreenHeight(Get.context!) -
                  44 -
                  133),
          //alignment: Alignment.center,
          child: ValueListenableBuilder(
            valueListenable: mobileScannerController.torchState,
            builder: (context, TorchState state, child) {
              String torchIconStr = state == TorchState.off
                  ? 'assets/images/scan/torch_light_off.png'
                  : 'assets/images/scan/torch_light_on.png';
              return Image.asset(
                torchIconStr,
                width: 54,
              );
            },
          ),
        ),
      ),
    );
  }

  //拿到二维码里面的信息以后逻辑
  void getCodeFormPic(String codeString) {
    animationController.stop();
    if (codeString.isNotEmpty) {
      toast('识别出的二维码：$codeString');
    } else {
      toast('未识别到能匹配到二维码，扫码失败');
      Future.delayed(const Duration(seconds: 2)).then((value) {
        Get.back();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
      reverseDuration: const Duration(seconds: 3),
    );

    //.1创建位移的tween，值必须是double类型
    _animation = Tween(
            begin: 0.0,
            end: ScreenSizeUtils.deviceScreenHeight(Get.context!) -
                ScreenSizeUtils.safeStatusScreenHeight(Get.context!) -
                44 -
                133)
        .animate(animationController);
    //开始动画
    animationController.repeat();
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }
}
